#!/usr/bin/env python
#coding=utf-8

#main method
from simulateDatabase import Database
import excute
import os
import platform

if __name__ == '__main__':
	###############################################################################
	#simulate database
	print "database initiating..."
	database = Database.Connect()
	###############################################################################
	##pause code##
	#pause = raw_input("pause")

	excute.importData()
	while 1:
		inputData = raw_input("Please input the filename of fig that you want to extract the keyword(Input \"end\" to quit)\n")
		if inputData == "end":
			break
		else:
			ontologies = raw_input("Please input the ontologies\n")
			resultType = raw_input("If you want to return a Json, please input \"0\". If you want to see the result, please input \"1\"\n")
			result = excute.mainMethod(inputData, ontologies, database, resultType)
			if resultType == "1":
				for element in result:
					print element
				if platform.system() == 'Windows':
					path = os.path.dirname(os.getcwd()) + "\\Inform_result.dat"
				elif platform.system() == 'Linux':
					path = os.path.dirname(os.getcwd()) + "/Inform_result.dat"
				IsSave = raw_input("Do you want to save the result in a text[" + path + "]?(Y or N)\n")
				if IsSave == "Y" or IsSave == "y":
					f = file(path,'w+')
					for element in result:
						f.write(element + "\n")
					f.close()
			else:
				JsonType = raw_input("Do you want to output the original Json data?(Y or N)\n")
				if JsonType == "Y" or JsonType == "y":
					print result
				else:
					print "["
					for element in result:
						print "  {"
						print "    score: "+ element['score']
						print "    annotatedClasses: ["
						for classes in element['annotatedClasses']:
							print "    {"
							print "      @id: " + classes['@id']
							print "      links: {"
							print "        ontology: " + classes['links']['ontology']
							print "      }"
							print "    },"
						print "    ]"
						print "  },"
					print "]"

					if platform.system() == 'Windows':
						path = os.path.dirname(os.getcwd()) + "\\Json_result.dat"
					elif platform.system() == 'Linux':
						path = os.path.dirname(os.getcwd()) + "/Json_result.dat"
					IsSave = raw_input("Do you want to save the result in a text[" + path + "]?(Y or N)\n")
					if IsSave == "Y" or IsSave == "y":	
						f = file(path,'w+')
						f.write("[\n")
						for element in result:
							f.write("\t{\n")
							f.write("\t\tscore: "+ element['score'] + "\n")
							f.write("\t\tannotatedClasses: [\n")
							for classes in element['annotatedClasses']:
								f.write("\t\t{\n")
								f.write("\t\t\t@id: " + classes['@id'] + ",\n")
								f.write("\t\t\tlinks: {\n")
								f.write("\t\t\t\tontology: " + classes['links']['ontology'] + "\n")
								f.write("\t\t\t}\n")
								f.write("\t\t},\n")
							f.write("\t\t]\n")
							f.write("\t},\n")
						f.write("]\n")
						f.close()

#end